package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public InputStream processImg(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);

        Long bpmnInfoId = carPackageAudit.getBpmnInfoId();
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(bpmnInfoId);
        //高亮节点集合
        List<String> highLightedActivities =  new ArrayList<>();
        if(carPackageAudit.getStatus().equals(CarPackageAudit.STATUS_IN_ROGRESS)){
            highLightedActivities = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        }else{
            highLightedActivities = Collections.emptyList();
        }

        DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator();
        /**
         * bpmnModel : model 石油我们流程图节点信息
         * 第二个参数: 高亮节点集合
         * 第三个参数: 高亮连线集合
         *
         */
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        InputStream inputStream = defaultProcessDiagramGenerator.generateDiagram(bpmnModel,
                highLightedActivities,
                Collections.emptyList(),
                "宋体",
                "宋体",
                "宋体");
        return inputStream;

    }

    @Override
    @Transactional
    public void cancelApply(Long id) {
        // 状态判断 , 必须要在审核中
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if(!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("非法操作");
        }
        // 修改carPackageAudit状态
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);
        // 修改服务单项状态
        serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        // 删除流程实例
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"不要了");
    }

    @Override
    @Transactional
    public void audit(Long id, String info, Integer auditStatus) {
        //1 根据id查询数据
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //2 判断状态是否为审核中状态
        if(!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw new BusinessException("非法操作");
        }
        //调用activiti api去完成任务, 在完成任务的时候要设置流程变量
        Map<String,Object> map = new HashMap<>();
        map.put("auditStatus",auditStatus);

        // 获取当前节点任务, 完成任务设置流程变量
        Task currentTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        taskService.complete(currentTask.getId(),map);

        // 判断是审核通过还是审核拒绝
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            // 审批通过
            // 判断是否有下一个节点
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if(nextTask !=null){
                // 有下一个节点
                // 拿到节点审核人 设置carPackageAudit 当中
                carPackageAudit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }else{
                // 没有下一个节点
                carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
                // 修改服务单项状态改为重新调整
                serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }
            carPackageAudit.setInfo(carPackageAudit.getInfo() + " <br>" + ShiroUtils.getUser().getUserName() + " 审批同意 意见为: " + info);
        }else if(CarPackageAudit.STATUS_REJECT.equals(auditStatus)){
            // 审批拒绝
            carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            carPackageAudit.setInfo(carPackageAudit.getInfo() + " <br>" + ShiroUtils.getUser().getUserName() + " 审批拒绝 意见为: " + info);
            // 修改服务单项状态改为重新调整
            serviceItemMapper.changeAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
        }

        carPackageAudit.setAuditTime(new Date());
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);



    }


}
